package com.nbcio.iot.controller;

import com.nbcio.common.core.domain.R;
import com.nbcio.iot.ingest.IotIngestionService;
import com.nbcio.iot.protocol.mqtt.MqttClientManager;
import jakarta.annotation.PostConstruct;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/iot/mqtt")
@RequiredArgsConstructor
public class IotMqttController {

    private final MqttClientManager mqttClientManager;
    private final IotIngestionService ingestionService;

    @PostConstruct
    public void init() {
        mqttClientManager.setMessageListener((topic, payload) -> {
            log.info("[MQTT-CTL] dispatch to ingestion, topic={}", topic);
            ingestionService.handleIncoming(topic, payload);
        });
    }

    @PostMapping("/subscribe")
    public R<Void> subscribe(@RequestBody Map<String, String> body) {
        String topic = body.get("topic");
        mqttClientManager.subscribe(topic);
        return R.ok();
    }

    @GetMapping("/subscribe")
    public R<Void> subscribeGet(@RequestParam("topic") String topic) {
        mqttClientManager.subscribe(topic);
        return R.ok();
    }

    @PostMapping("/publish")
    public R<Void> publish(@RequestBody Map<String, Object> body) {
        String topic = (String) body.get("topic");
        String payload = (String) body.get("payload");
        if (topic == null || topic.isEmpty()) {
            return R.fail("发布主题不能为空");
        }
        if (topic.contains("+") || topic.contains("#")) {
            return R.fail("发布主题不能包含通配符(+, #)，请使用具体主题");
        }
        mqttClientManager.publish(topic, payload);
        return R.ok();
    }

    @GetMapping("/publish")
    public R<Void> publishGet(@RequestParam("topic") String topic, @RequestParam("payload") String payload) {
        if (topic == null || topic.isEmpty()) {
            return R.fail("发布主题不能为空");
        }
        if (topic.contains("+") || topic.contains("#")) {
            return R.fail("发布主题不能包含通配符(+, #)，请使用具体主题");
        }
        mqttClientManager.publish(topic, payload);
        return R.ok();
    }

    @GetMapping("/health")
    public R<String> health() {
        return R.ok("MQTT controller active");
    }
} 